#coding:utf-8
'''
Created on 2016-7-14

@author: hexq
'''

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
sys.setrecursionlimit(1000000)
import traceback
from caches import *

import cookielib
import urllib2
import zlib
import json
import time
import random
import threading
import socket

socket.setdefaulttimeout(10.0) 

class getListener(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.stopped = 0
    def run(self):
        print self.stopped
        if self.stopped == 0:
            get_urlroot_index()
    def stop(self):
        self.stopped = 1



class lszbHelper():

    #设置通商+民工事件+自动收粮的时间间隔
    sleepTime = 3
    
    

    def getCjAndOpener(self):
        self.cj = None
        self.opener = None
        self.cj = cookielib.LWPCookieJar()
        cookie_support = urllib2.HTTPCookieProcessor(self.cj) 
        self.opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
        urllib2.install_opener(self.opener)
    #发包
    def sendRequestAndGetResult(self,actions, parmas={}, field=''):
        try:
            root = getCache("root") 
            playerheaders = getCache('playerheaders')
            url = root
            parmass = parmas
            parmass['command'] = actions
            parmass = urlencode(parmass).encode('utf-8')
            
            request = urllib2.Request(url, parmass, headers = playerheaders) 
            
            global Max_Num
            Max_Num=6  
            page = -1
            #增加了网络阻塞放错机制
            for i in range(Max_Num):  
                try:  
                    page=urllib2.urlopen(request,timeout=5).read()  
                    break  
                except:  
                    if i < Max_Num-1:  
                        continue  
                    else :  
                        print 'URLError: <urlopen error timed out> All times is failed '
#             result_new  = zlib.decompress(urllib2.urlopen(request,timeout=5).read())
            if page == -1:
                self.sendRequestAndGetResult(actions, parmas, field)
            else:
                try:
                    result_new  = zlib.decompress(page)
                except Exception as e:
                    self.sendRequestAndGetResult(actions, parmas, field)
                    
                result = json.loads(result_new)
                new = json.dumps( result,ensure_ascii= False)
                if result['state'] == 4 or result is None:
                    prints(actions + '%' +new)
                    result = self.sendRequestAndGetResult(actions, parmas, field)
                setCache('result', result)
                if result['state'] == 0:
                    if result.has_key('msg'):
                        prints(actions+result['msg'])
                    elif result.has_key('data'):
                        if result['data'].has_key('msg'):
                            prints(actions+result['data']['msg'])
                return result
        except:
            f = open('errorSendRequest.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()

    #收粮食和银币
    def building(self):
        buildLists = [2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23,24,25]
        buildList = [2,3,4,5,6,7,8,9,10,11,12,13,25]
        for build in buildLists:
            try:
                aa = self.sendRequestAndGetResult('city@getBuildingInfo', {"buildingId":build})
                if aa['state'] == 1:
                    if build in buildList:
                        if aa['data'].has_key("harvestRes"):
                            if aa['data']['harvestRes']['curRes'] > 0:
                                self.sendRequestAndGetResult('city@harvestBuildingRes',{'buildingId':build})
                        #去火
                        if aa['data'].has_key('firePlayerInfo'):
                            self.sendRequestAndGetResult('city@outfire',{'buildingId':build})
                    #建造中用锤子
                    if aa['data'].has_key('upgradeLeftCd'):
                        self.sendRequestAndGetResult('city@useCdHammer',{'buildingId':build})
            except:
                f = open('errorBuilding.txt','a')
                traceback.print_exc(file=f)
                f.flush()
                f.close()
        del buildList
        
    #庆典中的处理收粮食和银币
    def building2(self):
        buildList = [15,16,17,2,3,4,5,6,7,8,9,10,11,12,13]
        for build in buildList:
            self.sendRequestAndGetResult('city@harvestBuildingRes',{'buildingId':build})
        del buildList
    #庆典
    def celebration(self):
        celebrationinfo  = self.sendRequestAndGetResult('celebration@getInfo')
        state = celebrationinfo['data']['celebrateInfo']['state']
        round = celebrationinfo['data']['celebrateInfo']['round']
        if state ==1 :
            prints('开始处理文官')
            self.wenguan()
            #如果不在庆典，尝试国战 
            prints('不在庆典中尝试国战')
            self.gobattle()
            
        #军工满，未开启
        elif state == 2:
#             #退出战斗
            self.gobattle()
            prints('准备庆典，国战开始撤退，山马叛不退')
            self.sendRequestAndGetResult('battle@retreateWorldBattle')
            self.sendRequestAndGetResult('battle@exitBattle')
            time.sleep(15)
#             prints('还在战斗期间，继续战斗完成后开庆典')
            #开庆典
            self.sendRequestAndGetResult('celebration@celebrate',{'isAuto':'false'})
            #发布通商
            self.sendRequestAndGetResult('trade@startTrade')
        #庆典中
        elif state == 3:
            self.upgradeBaowu()
            celeinfo = self.sendRequestAndGetResult('celebration@getInfo')['data']['celebrateInfo']
            gb = int(celeinfo['goldblock'])
            totalgb = int(celeinfo['goldToCopper'])
            
            if gb <= totalgb*0.65 and gb>=5:
                self.ifpurifySuccess()
                if gb * 2 <= (totalgb/2+totalgb/10):
                    self.ifpurifySuccess()
                if gb*4 <= (totalgb/2+totalgb/10):
                    self.ifpurifySuccess()
                    
            if int(celeinfo['celebrateEndTime']) < 15000 and int(celeinfo['celebrateEndTime']) >= 0:
                for i in range(15):
                    self.ifpurifySuccess() 
            
            if gb >= totalgb:
                self.sendRequestAndGetResult('celebration@getGoldCopper')
            
            #与玩家通商
            self.sendRequestAndGetResult('trade@startTrade')
            
            self.sendRequestAndGetResult('trade@getReward')
            specialBuild = [17,16,15]
            for build in specialBuild:
                self.sendRequestAndGetResult('city@harvestBuildingRes',{'buildingId':build})
            del specialBuild
            
            
            
           
    #投资酒馆武将
    def touziGeneral(self):
        getDbid = getCache('dbId')
        if len(getDbid) > 0:
            for goTouzi in getDbid:
                prints('礼物贿赂武将')
                self.sendRequestAndGetResult('tavern@giveRedGeneralMoney',{"dbId":goTouzi,"way":3})
                prints('开始投资贿赂位置'+str(getCache('pos'))+'的红将')
                self.sendRequestAndGetResult('tavern@giveRedGeneralMoney',{'way':1,'dbId':goTouzi})
                self.sendRequestAndGetResult('tavern@giveRedGeneralMoney',{'way':1,'dbId':goTouzi})
                aa = self.sendRequestAndGetResult('tavern@giveRedGeneralMoney',{'way':1,'dbId':goTouzi})
                #如果投资不在酒馆里的武将重新获取位置上的武将id
                if aa['state'] == 0:
                    if aa['data']['msg'] == "":
#                     if aa['data']['msg'] == "\"\"":
                        prints('该武将不在酒馆里了，试着掉雇佣接口')
                        self.sendRequestAndGetResult('tavern@hireRedGeneral',{"dbId":goTouzi})
#                         self.gettavern()
                
    #赌博3连成，则继续赌博
    def ifpurifySuccess(self):
        try:
            ifSucc = self.sendRequestAndGetResult('city@purifyGoldBlock')
            if ifSucc['state'] == 1:
                if ifSucc['data'].has_key('isSuc'):
                    if str(ifSucc['data']['isSuc']) == 'True':
                        setCache('ifpurify', getCache('ifpurify')+1)
                        if getCache('ifpurify') >= 3:
                            prints('连续赌博成功3次以上，继续来一次')
                            self.sendRequestAndGetResult('celebration@getGoldCopper')
                            self.ifpurifySuccess()
                else:
                    setCache('ifpurify',0)
                
        except Exception as e:
            f = open('errorifpurifySuccess.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
            
    #免费祭祀
    def dofete(self):
        try:
            feteList = self.sendRequestAndGetResult('fete@getInfo')['data']["feteList"]
            for fetes in feteList:
                if fetes.has_key('freeTimes'):
                    if fetes['freeTimes'] > 0:
                        self.sendRequestAndGetResult('fete@fete', {"feteId":fetes['id']})
        except Exception as e:
            f = open('errorifdofete.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
        
    #通商+民工事件
    def trade(self):
        try:
            worldInfo = self.sendRequestAndGetResult('world@getInfo')
            generals = worldInfo['data']['generals']
            battleId = ''
            if generals[0].has_key('battleId'):
                battleId = generals[0]['battleId']
                self.sendRequestAndGetResult('battle@viewBattle',{"battleId":battleId})
    
            tradeCities = []
            if 'cityTradeInfoList' in worldInfo['data']:
                for each in worldInfo['data']['cityTradeInfoList']:
                    if int(each['cityTradeInfo']['cityId']) <> 0:
                        tradeCities.append(each['cityTradeInfo']['cityId'])
            if len(tradeCities) > 0 :
                self.sendRequestAndGetResult('trade@trade',{"cityId":tradeCities[0]})
            del tradeCities
            worldInfo = self.sendRequestAndGetResult('world@getInfo')
            eventList = worldInfo['data']['wenguan']['eventlist']
    #         event = ''
    #         eachsss = [3,5,6,7,8,9,10,11]
            eachsss = getCache('CheckedWenguan')
            for each in eventList:
                #新军务
                if each['eventId'] in eachsss:
                    statess = int(each['state'])
                    cityId = int(each['cityId'])
                    if statess == 2:
                        self.sendRequestAndGetResult('pWenguanEvent@getReward',{"cityId":cityId})
                    elif statess == 1:
                        self.sendRequestAndGetResult('pWenguanEvent@start',{"cityId":cityId})
    #             #是否购买宝石文官
    #             elif each['eventId'] == 15:
    #                 if getCache('eventGem') is not None:
    #                     if str(getCache('eventGem')) == '1':
    #                         prints('购买宝石文官事件')
    #                         cityIds = each['cityId']
    #                         self.sendRequestAndGetResult('pWenguanEvent@start',{"cityId":int(cityIds)})
          
            #大丰收
            self.sendRequestAndGetResult('marble@digMarble',{"type":2})
            if getCache('needPlayerRole')%60 == 0:
                    #大理石
                    self.sendRequestAndGetResult('marble@digMarble',{"type":1})
            setCache('needPlayerRole', getCache('needPlayerRole') + 1)
        except Exception as e:
            f = open('errortrade.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
    #文官
    def wenguan(self):
        
        unlike_task = [4,8,12,16,21,26,28,29,30,31,32,33,34,35,36,38]
        wenguanlist = []
        results = self.sendRequestAndGetResult('prestige@getPanel')
        if results['state'] == 1:
            if results['data'].has_key('taskList'):
                wenguanlist = results['data']['taskList']
        
        if len(wenguanlist) > 0:
            for i in range(len(wenguanlist)):
                if wenguanlist[i].has_key('request'):
                    taskId =  wenguanlist[i]['request']['taskType']
                    #领取完成奖励
                    if wenguanlist[i]['request']['completed'] == 1:
                        pos = wenguanlist[i]['pos']
                        self.sendRequestAndGetResult('playerBattleTask@getReward',{'pos':str(pos)})
                    else:
                        #频道喊话任务
                        if taskId == 25:
                            self.sendRequestAndGetResult('chat@send',  {"target":"null","chatType":3,"msg":"12"})
                        #如果任务未完成并且为强化任意宝石的任务，则无脑的强化5次1星宝石
                        elif taskId == 37:
                            self.sendRequestAndGetResult('gem@upgradeMoreGem', {"gemId":1,"num":5})
                    #放弃不喜欢的任务
                    
                    if taskId in unlike_task:
                        pos = wenguanlist[i]['pos']
                        self.sendRequestAndGetResult('playerBattleTask@cancel',{'pos':str(pos)}) 
                    
    #使用兵书
    def upgradeWarcraft(self):
        if getCache('upgradeBingfas') is not None:
            for bingfas in getCache('upgradeBingfas'):
                isGold = "false"
                self.sendRequestAndGetResult('warcraft@upgradeWarcraft', {"isGold":isGold,"warcraftId":bingfas})
#             #isdigit为确认为数字字符
# #             if str(getCache('bingfa')).isdigit():
# #                 if str(getCache('bingfa')) <> '0':
#                     playerBaowu = self.sendRequestAndGetResult('playerBaowu@getInfo')
#                     if playerBaowu['state'] == 1:
#                         if playerBaowu['data'].has_key('warcraftBookNum'):
#                             warcraftBookNum = playerBaowu['data']['warcraftBookNum']
#                             warcraftBooks = playerBaowu['data']['warcraftBooks']
#                             for playerBaowus in warcraftBooks:
#                                 if str(playerBaowus['warcraftId']) ==  str(getCache('bingfa')):
#                                     #升级兵法
#                                     if int(playerBaowus['nowExp']) < int(playerBaowus['maxExp']) and str(playerBaowus['intro']) <> '':
#                                         if int(warcraftBookNum) >= playerBaowus['bookNeedOnce']:
#                                             #使用兵书升级
#                                             self.sendRequestAndGetResult('warcraft@upgradeWarcraft', {"isGold":'false',"warcraftId":str(getCache('bingfa'))})
#                                         else:
#                                             prints('兵书不足')  
#                                     else:
#                                         prints('该兵法已满')
    
    #赎回武将
    def getbackgeneral(self):
        generalpanellist = self.sendRequestAndGetResult('general@getGeneralPanel')['data']['glist']
        for k in range(len(generalpanellist)):
            if generalpanellist[k].has_key('captureCopper'):
                gid = generalpanellist[k]['generalId']
                self.sendRequestAndGetResult('general@recoverCapture',{'generalId':str(gid)})                
    
    
    #充值送金
    def payActivity(self):
        payActivitys = self.sendRequestAndGetResult('payActivity@getInfo')
        if payActivitys['state'] == 1:
            if payActivitys['data']['hasFreeBox'] == 1:
#                 prints('充值送金——有免费次数购买一次')
                self.sendRequestAndGetResult('payActivity@getFreeBox')
    
    #处理宝石
    def doGem(self):
        try:
            gems = self.sendRequestAndGetResult('gem@getInfo')
            if gems['state'] == 1:
                if gems['data'].has_key("gemList"):
                    for gem in gems['data']['gemList']:
                        if gem['gemId'] == 1:
                            if int(gem['num']) >=30:
                                for i in range(0,int(gem['num'])/20):
                                    prints('一宝石超过30个，开始合成')
                                    self.sendRequestAndGetResult('gem@upgradeMoreGem', {"gemId":1,"num":20})
                        elif gem['gemId'] == 2:
                            if int(gem['num']) >=20:
                                prints('二宝石超过20个，开始合成')
                                for i in range(20):
                                    self.sendRequestAndGetResult('gem@upgradeGem', {"gemId":2})
        except Exception as e:
            f = open('errordoGem.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
    #宝石倾销
    def gemDump(self):
        copperturntables = self.sendRequestAndGetResult('gemDump@getInfo')
        if copperturntables['state'] == 1:
            if copperturntables['data']['freeState'] == 1:
#                 prints('宝石倾销——有免费次数购买一次')
                self.sendRequestAndGetResult('gemDump@buy',{"lv":1})
    
    #兵书倾销
    def warcraftbookDump(self):
        copperturntables = self.sendRequestAndGetResult('warcraftbookDump@getInfo')
        if copperturntables['state'] == 1:
            if copperturntables['data'].has_key('hasFreeState'):
                if copperturntables['data']['hasFreeState'] == 1:
        #                 prints('兵书倾销——有免费次数购买一次')
                    self.sendRequestAndGetResult('warcraftbookDump@buy',{'lv':1})
    #草船借箭
    def caoChuan(self):
        try:
            caoChuan = self.sendRequestAndGetResult('caoChuan@getInfo')
            if caoChuan['state'] == 1:
                if caoChuan['data'].has_key('shipInfo'):
                    for chuans in caoChuan['data']['shipInfo']:
                        if chuans['type'] == 1:
                            if chuans['freeNum'] == 1:
                                self.sendRequestAndGetResult('caoChuan@start',{'type':1})
        except Exception as e:
            f = open('errorcaoChuan.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
            
    #草船借箭——兵书版
    def caoBook(self):
        try:
            caoChuan = self.sendRequestAndGetResult('caoBook@getInfo')
            if caoChuan['state'] == 1:
                if caoChuan['data'].has_key('shipInfo'):
                    for chuans in caoChuan['data']['shipInfo']:
                        if chuans['type'] == 1:
                            if chuans['freeNum'] == 1:
                                self.sendRequestAndGetResult('caoBook@start',{'type':1})
        except Exception as e:
            f = open('errorcaoBook.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
    #银币转盘
    def copperturntable(self):
        copperturntables = self.sendRequestAndGetResult('copperturntable@getInfo')
        if copperturntables['state'] == 1:
            if copperturntables['data'].has_key('hasFreeState'):
                if copperturntables['data']['hasFreeState'] == 1:
#                 prints('银币转盘——有免费次数购买一次')
                    self.sendRequestAndGetResult('copperturntable@play')
            if copperturntables['data'].has_key('needGold'):
                needGold = int(copperturntables['data']['needGold'])
                if int(getCache('yinbizhuanpanGold')) > needGold:
                    prints('未达到预定的显示金币，开始银币转盘转转转')
                    self.sendRequestAndGetResult('copperturntable@play')
                prints('停转')
    #祖传兵书
    def warcraftlvup(self):
        warcraftlvup = self.sendRequestAndGetResult('warcraftlvupDump@getInfo')
        if warcraftlvup['state'] == 1:
            if warcraftlvup['data']['hasFreeState'] == 1:
#                 prints('祖传兵书——有免费次数购买一次')
                self.sendRequestAndGetResult('warcraftlvupDump@buy',{"lv":1})
    #宴请兵法
    def warcraftCreater(self):
        warcraftlvup = self.sendRequestAndGetResult('warcraftCreater@getInfo')
        if warcraftlvup['state'] == 1:
            if warcraftlvup['data']['hasFreeState'] == 1:
#                 prints('宴请兵法——有免费次数购买一次')
                self.sendRequestAndGetResult('warcraftCreater@buy',{"id":1})
                
    #捞玉玺活动            
    def laoyuxi(self):
        try:
            laoyuxis = self.sendRequestAndGetResult('laoyuxi@getInfo')
            if laoyuxis['state'] == 1:
                if laoyuxis['data']['freeState'] == 1:
#                     prints('宴请兵法——有免费次数购买一次')
                    self.sendRequestAndGetResult('laoyuxi@buy',{"type":1})
        except Exception as e:
            f = open('errorlaoyuxi.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
    #军需品
    def militarySupply(self):
        warcraftlvup = self.sendRequestAndGetResult('militarySupply@getInfo')
        if warcraftlvup['state'] == 1:
            if warcraftlvup['data']['hasFreeState'] == 1:
#                 prints('军需品——有免费次数购买一次')
                self.sendRequestAndGetResult('militarySupply@buy',{"position":1})
    #银币倾销
    def copperDump(self):
        copperDumps = self.sendRequestAndGetResult('copperDump@getInfo')
        if copperDumps['state'] == 1:
            if copperDumps['data']['hasFreeState'] == 1:
#                 prints('银币倾销——有免费次数购买一次')
                self.sendRequestAndGetResult('copperDump@buyCopper',{"lv":1})
    
    
    #奇珍异宝         
    def generalTreasureActivity(self):
        copperDumps = self.sendRequestAndGetResult('generalTreasureActivity@getInfo')
        if copperDumps['state'] == 1:
            if copperDumps['data']['freeState'] == 1:
#                 prints('奇珍异宝——有免费次数购买一次')
                self.sendRequestAndGetResult('generalTreasureActivity@buy',{"lv":1,"dbId":0})
    
    #七擒孟获         
    def arrestMenghuo(self):
        copperDumps = self.sendRequestAndGetResult('arrestMenghuo@getInfo')
        if copperDumps['state'] == 1:
            if copperDumps['data']['freeState'] == 1:
#                 prints('七擒孟获——有免费次数购买一次')
                self.sendRequestAndGetResult('arrestMenghuo@randomArrest')
    #曹操起兵活动
    def helpCaocao(self):
        copperDumps = self.sendRequestAndGetResult('helpCaocao@getInfo')
        if copperDumps['state'] == 1:
            if copperDumps['data'].has_key('hasFreeBox'):
                if copperDumps['data']['hasFreeBox'] == 1:
    #                 prints('曹操起兵活动——有免费次数购买一次')
                    self.sendRequestAndGetResult('helpCaocao@getFreeBox')
    #元旦活动
    def newYears(self):
        newYear = self.sendRequestAndGetResult('newYear@getInfo')
        if newYear['state'] == 1:
            if newYear['data'].has_key('freeState'):
                if newYear['data']['freeState'] == 1:
    #                 prints('曹操起兵活动——有免费次数购买一次')
                    self.sendRequestAndGetResult('newYear@play')
    #捞宝物活动
    def laobaowu(self):
        try:
            laobaowus = self.sendRequestAndGetResult('laobaowu@getInfo')
            if laobaowus['state'] == 1:
                if laobaowus['data'].has_key('freeState'):
                    if laobaowus['data']['freeState'] == 1:
        #                 prints('曹操起兵活动——有免费次数购买一次')
                        self.sendRequestAndGetResult('laobaowu@buy',{"type":3})
                    else:
                        for i in range(0,10):
                            laobaowus = self.sendRequestAndGetResult('laobaowu@getInfo')
                            for info in laobaowus['data']['info']:
                                if info['type'] == 3:
                                    needGold = int(info['num'])
                                    if int(getCache('laobaowuGold')) > needGold:
                                        prints('未达到预定的显示金币，开始捞宝物')
                                        self.sendRequestAndGetResult('laobaowu@buy',{"type":3})
                                    else:
                                        prints('停捞')
        except Exception as e:
            f = open('laobaowu.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
    #三顾茅庐升级一个
    def threeDo(self,num):
        self.sendRequestAndGetResult('threeVisits@visitOne', {"num":num+1})
    #三顾茅庐（宝石版）升级一个
    def threeDo2(self,num):
        self.sendRequestAndGetResult('threeVisitsGem@visitOne', {"num":num+1})
        
    #三顾茅庐活动
    def threeVisits(self):
        pics = []
        threeVisitsss = self.sendRequestAndGetResult('threeVisits@getInfo')
        if threeVisitsss['state'] == 1:
            if str(getCache('three')) == '1':
                if threeVisitsss['data'].has_key('rewardState'):
                    if threeVisitsss['data']['rewardState'] == 1:
                        pic = threeVisitsss['data']['pic']
                        for p in pic:
                            pics.append(int(p))
                        pics2 = sorted(pics)
                        if pics2 == [1,2,2]:
                            for i in range(len(pic)):
                                if str(pic[i]) == '1':
                                    self.threeDo(i)
                        elif pics2 == [2,3,3]:
                            for i in range(len(pic)):
                                if str(pic[i]) == '2':
                                    self.threeDo(i)
                        elif pics2 == [2,3,4] or pics2 == [2,4,4]:
                            for i in range(len(pic)):
                                if str(pic[i]) == '2':
                                    self.threeDo(i)
                                    self.threeDo(i)
                                elif str(pic[i]) == '3':
                                    self.threeDo(i)
                        elif pics2 == [3,3,4] or pics2 == [3,4,4]:
                            for i in range(len(pic)):
                                if str(pic[i]) == '3':
                                    self.threeDo(i)
                        self.sendRequestAndGetResult('threeVisit@getReward')
                    elif threeVisitsss['data']['hasFreeState'] == 1:
                        prints('开始免费寻访')
                        self.sendRequestAndGetResult('threeVisits@visit')
                    elif threeVisitsss['data']['rewardState'] == 0:
                        needGold = int(threeVisitsss['data']['needGold'])
                        threeGold = int(getCache('threeGold'))
                        if needGold < threeGold:
                            prints('三顾茅庐（兵书版）未达选中金币，开始金币寻访')
                            self.sendRequestAndGetResult('threeVisits@visit')
        del pics
    #三顾茅庐活动
    def threeVisits2(self):
        pics = []
        threeVisitsss = self.sendRequestAndGetResult('threeVisitsGem@getInfo')
        if threeVisitsss['state'] == 1:
            if str(getCache('three2')) == '1':
                if threeVisitsss['data'].has_key('rewardState'):
                    if threeVisitsss['data']['rewardState'] == 1:
                        pic = threeVisitsss['data']['pic']
                        for p in pic:
                            pics.append(int(p))
                        pics2 = sorted(pics)
                        if pics2 == [1,2,2]:
                            for i in range(len(pic)):
                                if str(pic[i]) == '1':
                                    self.threeDo2(i)
                        elif pics2 == [2,3,3]:
                            for i in range(len(pic)):
                                if str(pic[i]) == '2':
                                    self.threeDo2(i)
                        elif pics2 == [2,3,4] or pics2 == [2,4,4]:
                            for i in range(len(pic)):
                                if str(pic[i]) == '2':
                                    self.threeDo2(i)
                                    self.threeDo2(i)
                                elif str(pic[i]) == '3':
                                    self.threeDo2(i)
                        elif pics2 == [3,3,4] or pics2 == [3,4,4]:
                            for i in range(len(pic)):
                                if str(pic[i]) == '3':
                                    self.threeDo2(i)
                        self.sendRequestAndGetResult('threeVisitsGem@getReward')
                    elif threeVisitsss['data']['hasFreeState'] == 1:
                        prints('开始免费寻访')
                        self.sendRequestAndGetResult('threeVisitsGem@visit')
                    elif threeVisitsss['data']['rewardState'] == 0:
                        needGold = int(threeVisitsss['data']['needGold'])
                        threeGold2 = int(getCache('threeGold2'))
                        if needGold < threeGold2:
                            prints('三顾茅庐（宝石版）未达选中金币，开始金币寻访')
                            self.sendRequestAndGetResult('threeVisitsGem@visit')
        del pics
    #国防建设
    def guofang(self):
        try:
            mycity = getCache('player_id')
            construnctinfoss = self.sendRequestAndGetResult('enfeoff@getConstructInfo',{'dPlayerId':str(mycity)})
            if construnctinfoss['data'].has_key('constructInfo'):
                if construnctinfoss['data']['constructInfo'].has_key('constructQueue'):
                    construnctinfos = construnctinfoss['data']['constructInfo']['constructQueue']
                    if len(construnctinfos) == 0:
                        self.sendRequestAndGetResult('enfeoff@startConstruct',{'type':str(getCache('guofang'))})
                    else:
                        for construnctinfo in construnctinfos:
                            state = construnctinfo['state']
                            lefttimes = construnctinfo['constructLeftTime']
                            pos = construnctinfo['pos']
                            if (state == 0 and lefttimes == 0) or len(construnctinfos) < 3:
                                self.sendRequestAndGetResult('enfeoff@startConstruct',{'type':str(getCache('guofang'))})
                            if state == 3:
                                self.sendRequestAndGetResult('enfeoff@damnIt',{"pos":pos})
                        
                            if state == 4:
                                self.sendRequestAndGetResult('enfeoff@getConstructReward',{"pos":pos}) 
        except Exception as e:
            f = open('errorguofang.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
            
    #小秘书领取攻城奖励
    def secretary(self):
        secretarys = self.sendRequestAndGetResult('secretary@getInfo')
        if secretarys['state'] == 1:
            if secretarys['data']['state'] <> 1:
                prints('未开启小秘书，开启默认的小秘书')
                self.sendRequestAndGetResult('secretary@startTask',{"conf":"3:2"})
            if secretarys['data'].has_key('winInfos'):
                if len(secretarys['data']['winInfos']) > 0:
                    self.sendRequestAndGetResult('secretary@takeCityReward', {"pos":1})
            prints('领取每天免费小秘书次数')
            if secretarys['data'].has_key('hasFreeFete'):
                if secretarys['data']['hasFreeFete'] == 1:
                    aa = self.sendRequestAndGetResult('secretary@getFreeFete')
#                     if aa['state'] == 1:
#                         prints('去干免费小经验车队')
#                         setCache('xiaojingyan', 1)
    #跨服远征
    def kfyz(self):
        returns = 0
        try:
            kfyzs = self.sendRequestAndGetResult('kfyz@getEnemyList')
            min = 100
            kfmubiao = 0
            if kfyzs['state'] == 1:
                if kfyzs['data'].has_key('kfyzEnemys'):
                    if len(kfyzs['data']['kfyzEnemys']) > 0:
                        for kfyzEnemys in kfyzs['data']['kfyzEnemys']:
                            playerLevel = kfyzEnemys['playerLevel']
                            if playerLevel < min:
                                kfmubiao = kfyzEnemys['cid']
                                serverName = kfyzEnemys['serverName']
                                serverId = kfyzEnemys['serverId']
                                playerName = kfyzEnemys['playerName']
                                min = playerLevel
            else:
                return 0
            if int(getCache('playerLvs')) < min + 5:
                kfmubiao = 0
            if kfmubiao <> 0:
                prints('本次跨服远征目标：%s_%s的%s等级为%s' % (serverName,serverId,playerName,min))
                if str(getCache('ifFenbin')) == '1':
                    aa = self.sendRequestAndGetResult('kfyz@attack', {"cid":kfmubiao,"type":1})
                else:
                    aa = self.sendRequestAndGetResult('kfyz@attack', {"cid":kfmubiao})
                print aa
                returns = 1
            else:
                returns = 0
        except Exception as e:
            f = open('errorkfyz.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
            return returns
        return returns
    #开始放兵
    def toubing(self,isInbattle,noArmyBattle,isInbrawls,battleid):
        prints('战术放起来')
        self.sendRequestAndGetResult('battle@viewBattle',{"battleId":battleid})
        self.sendRequestAndGetResult('battle@usezhanshu',{"zhanshuId":14,"battleId":str(battleid)})
        if isInbattle == 1 and noArmyBattle == 0:
            for i in range(0,10):
                battleinfo = self.sendRequestAndGetResult('battle@getBInfo')
                if battleinfo['state'] == 1:
                    break
            if battleinfo.has_key('state'):
                if battleinfo['state'] == 1:
                    if battleinfo.has_key('data'):
                        if battleinfo['data'].has_key('glist'):
                            glist = battleinfo['data']['glist']
                            glistss = ["0:0","0:0","0:0","0:0","0:0"]
                            prints("开始放兵")
                            for glists in glist :
                                if glists.has_key('id'):
                                    gid =  glists['id']
                                    glistss[glists['position']-1] = str(glists['id'])+":"+str(glists['troopNum'])
                            for i in range(len(glistss)):
                                gid =  int(glistss[i].split(":")[0])
                                if int(glistss[i].split(":")[1]) > 0:
                                    for j in range(int(glistss[i].split(":")[1])):
                                        self.sendRequestAndGetResult('battle@addGeneral',{'type':0,'gId':str(gid),'battleId':str(battleid)})
                                    break
        #5v5中
        elif isInbrawls == 1:
            self.sendRequestAndGetResult('battle@useWine',{"isGold":"false","battleId":battleid})
            glistssss = self.sendRequestAndGetResult('battle@getWaitedGeneralInfo',{"battleId":battleid})
            if glistssss.has_key('data'):
                if glistssss['data'].has_key('waitedList'):
                    glists = glistssss['data']['waitedList']
                    prints('5V5开始放兵')
                    for glist in glists:
                        self.sendRequestAndGetResult('battle@addGeneral',{'type':0,'gId':str(glist['gid']),'battleId':str(battleid)})
                        self.sendRequestAndGetResult('battle@addGeneral',{'type':0,'gId':str(glist['gid']),'battleId':str(battleid)})
    
        self.sendRequestAndGetResult('battle@usezhanshu',{"zhanshuId":14,"battleId":str(battleid)})
        self.sendRequestAndGetResult('battle@viewBattle',{"battleId":battleid})
    #山马叛、小经验
    def shan(self,worldInfo):
        try:
            if worldInfo['data'].has_key('eventInfo'):
                shanmapan_evnetlist = worldInfo['data']['eventInfo']
    #             if getCache('xiaojingyan') == 1:
                for events in shanmapan_evnetlist:
                    if events['type'] == 100 and (str(events['isFree']) == 'True' or str(events['isFree']) == 'true'):
                        prints('前去小经验车队')
                        aa = self.sendRequestAndGetResult('playerEvent@startEvent',{'cityId':events['cityId']})
                        if aa['state'] == 1:
                            prints('免费经验车队打完！！！')
    #                         setCache('xiaojingyan', 0) 
                         
                for i in range(2):
       
                    if shanmapan_evnetlist[i]['nextEnterTime'] == 0:
                        cityid = shanmapan_evnetlist[i]['cityId']
                           
                        start_event = self.sendRequestAndGetResult('playerEvent@startEvent',{'cityId':str(cityid)})
                        if start_event['state'] == 1:
                            battleId = start_event['data']['battleId']
                            self.sendRequestAndGetResult('battle@viewBattle',{'battleId':str(battleId)})
                            time.sleep(1)
                            self.sendRequestAndGetResult('battle@notice',{'noticeKey':'sayover','battleId':str(battleId)})
                            if str(shanmapan_evnetlist[i]['name']) == '兵营'  or str(shanmapan_evnetlist[i]['name']) == '马贼':
                                #退出兵营、马贼
                                self.sendRequestAndGetResult('battle@retreateJiaoFeiBattle')
                                self.sendRequestAndGetResult('battle@exitBattle')
                                 
        except Exception as e:
            f = open('errorshanmapan.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
    
    #获取5V5
    def fiveV5(self,worldInfo):
        try:
            if worldInfo['data'].has_key('brawlsArray'):
                if len(worldInfo['data']['brawlsArray']) > 0:
                    brawlsArray = worldInfo['data']['brawlsArray']
                    doforce = '0' 
                    for brawlss in brawlsArray:
                        brawls = brawlss['brawlsInfo']
                        forcess = []
                        forcess.append(str(brawls['force1']))
                        forcess.append(str(brawls['force2']))
                        #判断玩家的国家在进行5V5然后可以报名，可以审批
                        if str(getCache('force_id')) in forcess: 
                            for forcesss in forcess:
                                if str(getCache('force_id')) <> forcesss:
                                    doforce = str(forcesss)
                        if doforce <> '0':
                            #判断准备期间可以去报名审批
                            prints('你们国家存在5V5开始报名与审批操作')
                            brawlsinfo = self.sendRequestAndGetResult('brawls@getInfo', {"defForceId":doforce})['data']
                            if brawlsinfo.has_key('myState'):
                                if brawlsinfo['myState'] == 1:
                                    #已经报名
                                    setCache('brawlsState', '1')
                                else:
                                    setCache('brawlsState', '0')
                            else:
                                setCache('brawlsState', '0')
        except Exception as e:
            f = open('errorFiveV5.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
    def changshiyuanzheng(self):
        returns = 0
        try:
            worldInfo = self.sendRequestAndGetResult('world@getYzList')
            getIsAccFull = self.sendRequestAndGetResult('player@getIsAccFull')
            if getIsAccFull['state'] == 1:
                if getIsAccFull['data'].has_key('percent'):
                    if getIsAccFull['data']['percent'] >= 100:
#                 if getIsAccFull['data'].has_key('isfull'):
#                     if getIsAccFull['data']['isfull'] == 1:
                        prints('远征进度满，开始尝试远征')
                        while getCache('playerLvs') is None:
                                time.sleep(1)
                        prints('获取玩家等级为'+str(getCache('playerLvs'))+'级')
                        #跨服远征
                        kfyzReturn = self.kfyz()
                        #如果没有跨服远征目标则进行本地远征
                        if kfyzReturn == 1:
                            returns = 1
                        else:
                            prints('没有跨服远征目标则进行本地远征')
#                             returns = 1
#                         else:
                            #远征
                            yuanzhenglist = []
                            yuanzhenglist1 = []
                            yuanzhenglist2 = []
                            prints(str(getCache('playerLvs')))
                            
                            if int(getCache('playerLvs')) >= 42:
                                max = int(getCache('playerLvs')) -1
                                min = 42
                            else:
                                max = int(getCache('playerLvs')) -1
                                min = int(getCache('playerLvs')) -9
                            for i in range(len(worldInfo['data']['vsList'])) :
                                citiess = worldInfo['data']['vsList'][i]
#                                 czs = {}
#                                 if citiess.has_key('czs'):
#                                     czss = citiess['czs']
#                                     if len(czss) >=1 :
#                                         czs = czss[0]
                                try:
                                    if citiess.has_key('chengzhuInfo'):
#                                         if citiess['chengzhuInfo'].has_key('bingshuReward'):
#                                         if str(citiess["forceId"]) != str(getCache('force_id')) and citiess['chengzhuInfo'].has_key('bingshuReward') and int(citiess['chengzhuInfo']['playerLv']) >= min and int(citiess['chengzhuInfo']['playerLv']) <= max :
                                        if citiess['chengzhuInfo'].has_key('bingshuReward') and int(citiess['chengzhuInfo']['playerLv']) >= min and int(citiess['chengzhuInfo']['playerLv']) <= max :
                                            #如果不在线玩家则加进入yuanzhenglist1
                                            if not citiess['chengzhuInfo'].has_key('online'):
                                                if str(citiess['chengzhuInfo']['playerName']) not in getCache('exceptss'):
                                                    yuanzhenglist1.append(citiess['chengzhuInfo']['playerId'])
                                            else:#如果在线玩家则加进入yuanzhenglist2
                                                if str(citiess['chengzhuInfo']['online']) == 'True':
                                                    if str(citiess['chengzhuInfo']['playerName']) not in getCache('exceptss'):                                             
                                                        yuanzhenglist2.append(citiess['chengzhuInfo']['playerId'])
                                                else:#如果不在线玩家则加进入yuanzhenglist1
                                                    if str(citiess['chengzhuInfo']['playerName']) not in getCache('exceptss'):
                                                        yuanzhenglist1.append(citiess['chengzhuInfo']['playerId'])
                                except Exception as e:
                                    f = open('errorchangshiyuanzheng2.txt','a')
                                    traceback.print_exc(file=f)
                                    f.flush()
                                    f.close()
                            generalIds = ''
                            #如果不在线列表无玩家则取在线玩家列表
                            if yuanzhenglist1 == []:
                                yuanzhenglist = yuanzhenglist2
                            else:
                                yuanzhenglist = yuanzhenglist1
                            forces = [1,2,3]
                            if yuanzhenglist == []:
                                for f in forces:
                                    if str(f) <> str(getCache('force_id')):
                                        ab = self.sendRequestAndGetResult("vs@getCaptialVsInfo" ,{"forceId":f})
                                        prints(ab)
                                        if ab['state'] == 1:
                                            if ab['data'].has_key("defList"):
                                                defListss = ab['data']['defList']
                                                for defs in defListss:
                                                    if int(defs['playerLv']) >= min and int(defs['playerLv']) <= max:
                                                        yuanzhenglist.append(defs["playerId"])
                            if yuanzhenglist <> []:#如果有远征目标则远征
                                prints('确定敌方列表：%s'%yuanzhenglist)
                                if len(yuanzhenglist) > 0:
                                    dPlayerId = random.choice(yuanzhenglist)
                                    self.getGenerals()
                                    prints("本服远征确定地方玩家PId：%s"%dPlayerId)
                                    prints('开始远征')
                                    if str(getCache('ifFenbin')) == '1':
                                        yuanzhenginfo = self.sendRequestAndGetResult('vs@startVs',{'vsPid':str(dPlayerId),'generalIds':getCache('generalIds'),"type":1})
                                    else:
                                        yuanzhenginfo = self.sendRequestAndGetResult('vs@startVs',{'vsPid':str(dPlayerId),'generalIds':getCache('generalIds')})
                                    if yuanzhenginfo['state'] == 0:
                                        if yuanzhenginfo.has_key('data'):
                                            if yuanzhenginfo['data'].has_key('msg'):
                                                if yuanzhenginfo['data']['msg'] == '武将不存在或武将被抓捕或上阵不满5人':
                                                    returns = 0
                                    else:
                                        returns = 1
                                else:#如果没有远征目标则1V2
                                    returns = self.oneVtwo(worldInfo)
                            else:#如果没有远征目标则1V2
                                returns = self.oneVtwo(worldInfo)
                            del yuanzhenglist
                            del yuanzhenglist1
                            del yuanzhenglist2 
        except Exception as e:
            f = open('errorchangshiyuanzheng.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
            return returns
        return returns
    
    #加入国战
    def addguozhan(self):
        yezhan = 0
        atts = 0
        attackcitylist = []
        CheckedCityType = []
        if getCache('CheckedCityType') is not None:
            CheckedCityType = getCache('CheckedCityType')
        try:
            worldgetInfo = self.sendRequestAndGetResult('world@getInfo')
            if worldgetInfo['state'] == 1:
                if worldgetInfo['data'].has_key('cities'):
                    citiess = worldgetInfo['data']['cities']
                    corpsLists = worldgetInfo['data']['corpsInfo']['corpsList']
                    for corpsList in corpsLists:
                        if str(corpsList['attackForceId']) == str(getCache('force_id')):
                            for aa in citiess:
                                if corpsList['cityId'] == aa['cityId']:
                                    if aa.has_key('t'):
                                        if  aa['t'] in CheckedCityType:
                                            if aa.has_key('attPgNum'):
                                                #我国攻打城池小于4个人在场才进入
                                                if aa['attPgNum'] < 4:
                                                    #加入夜战
                                                    if aa.has_key('isNightBattle'):
                                                        if str(aa['isNightBattle']) == 'True' or str(aa['isNightBattle']) == 'true':
                                                            yezhan = aa['cityId']
                                                    attackcitylist.append(aa['cityId'])
            prints(attackcitylist)
            if yezhan <> 0:
                atts = yezhan
            elif attackcitylist:
                atts = str(random.choice(attackcitylist))
            if atts <> 0:
                #前往城战
                result = self.sendRequestAndGetResult('world@quickmoveGeneral',{'cityId':atts})
                if str(result['data']['msg']) == "大决战开始了，请去参加大决战":
                    citiesssss = self.sendRequestAndGetResult('world@getInfo')['data']['cities']
                    for aa in citiesssss:
                        if aa.has_key("state"):
                            if aa['state'] == 3:
                                prints('前往大决战')
                                self.sendRequestAndGetResult('world@quickmoveGeneral',{'cityId':aa['cityId']})
        except Exception as e:
            f = open('errorGuozhan.txt','a')
            traceback.print_exc(file=f)
            f.flush()
        del attackcitylist
        del CheckedCityType
    #战斗处理
    def gobattle(self):
        worldInfo = self.sendRequestAndGetResult('world@getInfo')   
        isInbrawls = 0
        isInbattle = 0
        #战斗中，尝试上兵并施放战术
        if worldInfo['data'].has_key('brawlsArray'):
            if len(worldInfo['data']['brawlsArray']) >0:
                brawlsInfos = worldInfo['data']['brawlsArray'][0]['brawlsInfo']
                if brawlsInfos.has_key('force1') and brawlsInfos.has_key('force2'):
                    if str(getCache('force_id')) == str(brawlsInfos['force1']) or str(getCache('force_id')) == str(brawlsInfos['force2']):
                        if brawlsInfos['prepareTime']<=0:
                            if getCache('brawlsState') is not None:
                                if getCache('brawlsState') == '1':
                                    #战斗开始中
                                    isInbrawls = 1
                                else:
                                    isInbrawls = 2
                            else:
                                isInbrawls = 2
                        else:
                            #报名中
                            isInbrawls = 2
        noArmyBattle = 0
        if worldInfo['data'].has_key('generals'):
            if worldInfo['data']['generals'][0].has_key('yzBattleId') or worldInfo['data']['generals'][0].has_key('battleId'):
                isInbattle = 1
                if worldInfo['data']['generals'][0].has_key('yzBattleId'):
                    noArmyBattle = 1
        #判断是否在战斗中或者在5v5决战中
        if isInbattle == 1 or isInbrawls == 1:
            if isInbrawls == 1:
                prints('5v5决战中')
                self.sendRequestAndGetResult("battle@retreateWorldBattle")
                self.sendRequestAndGetResult('battle@exitBattle')
            battleid = ''
            if worldInfo['data'].has_key('generals'):
                if worldInfo['data']['generals'][0].has_key('brawlsBattleId'):
                    battleid = worldInfo['data']['generals'][0]['brawlsBattleId']
                elif worldInfo['data']['generals'][0].has_key('yzBattleId'):
                    battleid = worldInfo['data']['generals'][0]['yzBattleId']
                elif worldInfo['data']['generals'][0].has_key('battleId'):
                    battleid = worldInfo['data']['generals'][0]['battleId']
            
            #开始放兵
            self.toubing(isInbattle,noArmyBattle,isInbrawls,battleid)
            
            prints('开始谎报')
            self.sendRequestAndGetResult('cityBattle@useHuangBao',{"battleId":str(battleid)})
            prints('开始使用炸弹')
            self.sendRequestAndGetResult('cityBattle@useCityBoom',{"battleId":str(battleid)})
            
            #开始放兵与战术
            self.toubing(isInbattle,noArmyBattle,isInbrawls,battleid)
            
            prints('开始使用内讧')
            self.sendRequestAndGetResult('cityBattle@useLiuYan',{"battleId":str(battleid)})
            
            #开始放兵与战术
            self.toubing(isInbattle,noArmyBattle,isInbrawls,battleid)
            
            #攻城榜宝箱
            prints('尝试开攻城宝箱')
            self.sendRequestAndGetResult('cityBattle@getRankingReward',{'battleId':str(battleid)})
            
            if getCache('fires') is not None:
                if str(getCache('fires')) == '1':
                    prints('尝试烧火（花金哦！！！）')
                    self.sendRequestAndGetResult('city@fire')   
            
            #开始放兵
            self.toubing(isInbattle,noArmyBattle,isInbrawls,battleid)
            try:
                generalpanellist = self.sendRequestAndGetResult('general@getGeneralPanel')['data']['glist']
                for k in range(len(generalpanellist)):
                    if generalpanellist[k].has_key('captureCopper'):
                        prints('战斗中有将被抓，开始撤退，等待15秒')
                        self.sendRequestAndGetResult("battle@retreateWorldBattle")
                        self.sendRequestAndGetResult('battle@exitBattle')
                        time.sleep(15) 
            except Exception as e:
                aa = 1
        #不在战斗，尝试远征、山马叛、国战
        else:
            worldInfo = self.sendRequestAndGetResult('world@getInfo')
            if worldInfo['data'].has_key('wenguan'):
                eventList = worldInfo['data']['wenguan']['eventlist']
                for each in eventList:
                    prints('开始募兵')
                    if each['eventId'] == 4:
                        cityIds = each['cityId']
                        self.sendRequestAndGetResult('pWenguanEvent@start',{"cityId":int(cityIds)})
            #获取5V5
            self.fiveV5(worldInfo)
            prints('不在国战，开始尝试远征')
            returns = self.changshiyuanzheng() 
            #各种远征没有目标的情况下去山马叛、国战
            if returns ==0:
                prints('不在国战，不在远征，开始尝试山马叛')
                self.shan(worldInfo)
                #加入国战
                prints('不在国战，不在远征，开始尝试山马叛')
                #加入国战
                self.addguozhan()
            
    def getplayerlv(self):
        try:
            players = int(getCache('players'))
            getRoleInfo = self.sendRequestAndGetResult('player@getRoleList')
            if getRoleInfo.has_key('data'):
                if len(getRoleInfo['data']['playerList']) < players:
                    prints('没有第%s个角色，现帮您选择第%s个角色的信息'%(players,players-1))
                    playerLvs = getRoleInfo['data']['playerList'][players-2]['playerLv']
                    player_id = getRoleInfo['data']['playerList'][players-2]['playerId']
                    playerName = getRoleInfo['data']['playerList'][players-2]['playerName']
                    playerForceId = getRoleInfo['data']['playerList'][players-2]['playerForceId']
                else:
                    prints('已帮您选择第%s个角色的信息'%players)
                    playerLvs = getRoleInfo['data']['playerList'][players-1]['playerLv']
                    player_id = getRoleInfo['data']['playerList'][players-1]['playerId']
                    playerName = getRoleInfo['data']['playerList'][players-1]['playerName']
                    playerForceId = getRoleInfo['data']['playerList'][players-1]['playerForceId']
                    
        except Exception as e:
            playerLvs  = 40
            player_id  = 1
            playerName  = '不存在，请重新去配置吧'
            playerForceId = 3
        setCache('playerLvs', playerLvs)
        setCache('player_id', player_id)
        setCache('playerName', playerName)
        setCache('force_id', playerForceId)
    
    def gettavern(self): 
        getpos = getCache('pos')
        dbId = []
        taverns = []
        if isinstance(getpos, list):
            tavern = self.sendRequestAndGetResult('tavern@getTavernInfo')
            if tavern['state'] == 1:
                for tavernEvents in tavern['data']['tavernEvents']: 
                    taverns.append(int(tavernEvents['dbId']))
                taverns.sort()
                if taverns <> []:
                    for posss in getpos:
                        poss = None
                        if str(posss) != '0': 
                            poss = None
                            if int(posss)-1 > 10 or int(posss)-1 <0:
                                poss = None
                            else:
                                poss = int(posss)-1
                        if poss is not None:
                            dbId.append(taverns[poss])
        setCache('dbId', dbId)
        del dbId
        del taverns
    
    
    def oneVtwo(self,worldInfo):
        returns = 0
        try:
            mubiao = ''
            prints('选不到远征目标，开始1v2')
            getAllMelee = worldInfo['data']
            minlV = 1000
    #         prints(getAllMelee)
            if getAllMelee.has_key('meleeList'):
                meleeList = getAllMelee['meleeList']
                if len(meleeList) > 0:
                    for i in range(0,len(meleeList)):
                        if int(getCache('playerLvs')) > int(meleeList[i]['mainDefInfo']['playerLv'])+2 and int(getCache('playerLvs')) > int(meleeList[i]['otherDefInfo']['playerLv'])+2 and int(meleeList[i]['mainDefInfo']['playerLv'])+int(meleeList[i]['otherDefInfo']['playerLv']) < minlV:
                            if str(meleeList[i]['mainDefInfo']['playerName']) not in getCache('exceptss') and str(meleeList[i]['otherDefInfo']['playerName']) not in getCache('exceptss'):
                                mubiao = meleeList[i]['mainDefInfo']['playerId']
                                minlV = int(meleeList[i]['mainDefInfo']['playerLv'])+int(meleeList[i]['otherDefInfo']['playerLv'])
                else:
                    prints('木有1v2目标')
            if mubiao == '':
                if getAllMelee.has_key('meleeList'):
                    meleeList = getAllMelee['meleeList']
                    if len(meleeList) > 0:
                        for i in range(0,len(meleeList)):
                            if int(getCache('playerLvs')) > int(meleeList[i]['mainDefInfo']['playerLv'])+2 and int(getCache('playerLvs')) > int(meleeList[i]['otherDefInfo']['playerLv'])+2 and int(meleeList[i]['mainDefInfo']['playerLv'])+int(meleeList[i]['otherDefInfo']['playerLv']) < minlV:
                                if str(meleeList[i]['mainDefInfo']['playerName']) not in getCache('exceptss') and str(meleeList[i]['otherDefInfo']['playerName']) not in getCache('exceptss'):
                                    mubiao = meleeList[i]['mainDefInfo']['playerId']
                                    minlV = int(meleeList[i]['mainDefInfo']['playerLv'])+int(meleeList[i]['otherDefInfo']['playerLv'])
            
            generalIds = ''
            if mubiao <> '':
                self.getGenerals()
                prints("1V2开始攻击："+str(mubiao))
                yuanzhenginfo=self.sendRequestAndGetResult('melee@startMeleeBattle', {"generalIds":getCache('generalIds'),"enemyId":mubiao})
                if yuanzhenginfo['state'] == 0:
                    if yuanzhenginfo.has_key('data'):
                        if yuanzhenginfo['data'].has_key('msg'):
                            if yuanzhenginfo['data']['msg'] == '武将不存在或武将被抓捕或上阵不满5人':
                                returns = 0
                else:
                    returns = 1
            else:
                prints('木有1v2目标')
                returns = 0
        except Exception as e:
            f = open('error1V2.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
            return returns
        return returns
    def getGenerals(self):
        generalIds = [0,0,0,0,0]
        try:
            if getCache('generalIds') is None or getCache('generalIds') == '':
                getConstructInfo = self.sendRequestAndGetResult('general@getGeneralPanel')
                attLists = getConstructInfo['data']['glist']
                for attList in attLists :
                    if attList['generalId'] is not None or attList['generalId'] <> '':
                        generalIds[attList['position']-1] = attList['generalId']
                generalIds = str(generalIds)
                generalIds = generalIds.replace(' ', '')
                generalIds = generalIds.replace('0,]', '')
                generalIds = generalIds.replace('[0,', '')
                generalIds = generalIds.replace('[', '')
                generalIds = generalIds.replace(']', '')
                generalIds = generalIds.replace('0,', '')
                generalIds = generalIds.replace(',0', '')
                setCache('generalIds', generalIds)
        except Exception as e:
            f = open('errorgetGenerals.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
        prints('确定本方武将列表为 %s'%getCache('generalIds'))
        
    
    #升级主城建筑
    def upgradeBuilding(self):
        try:
            cityUpgrade = getCache('cityUpgrade')
            if not isinstance(cityUpgrade, list):
                cityUpgrade = eval(cityUpgrade)
            getInfo = self.sendRequestAndGetResult("city@getInfo")
            if getInfo['state'] == 1:
                if getInfo['data'].has_key("buildings"):
                    buildingQueueNum= getInfo['data']['buildingQueueNum']
                    nowBuildingNum = 0
                    buildings = getInfo['data']['buildings']
                    min = 9999
                    needUpgrade = 0
                    for building in buildings:
                        canbuild1 = 0
                        canbuild2 = 0
                        if building.has_key('upgradeLeftCd'):
                            if building['upgradeLeftCd'] <= 0:
                                canbuild1 = 1
                            else:
                                nowBuildingNum = nowBuildingNum + 1
                        else:
                            canbuild1 = 1
                        if building.has_key('isNoWork'):
                            if building['isNoWork'] == 0:
                                canbuild2 = 1
                        else:
                            canbuild2 = 1
                        if canbuild1 == 1 and canbuild2 == 1:
                            if building['bid'] in cityUpgrade:
                                if building['bid'] not in getCache("expBuild"):
                                    if building['bid'] == 14:
                                        self.sendRequestAndGetResult('city@upgradeBuilding', {"buildingId":14})
                                    elif building.has_key('lv'):
                                        if building['lv'] <= min:
                                            needUpgrade = building['bid']
                                            min = building['lv']
#                     prints(nowBuildingNum)
#                     prints(buildingQueueNum)
                    if nowBuildingNum < buildingQueueNum:
                        #开始升级建筑
                        if needUpgrade in cityUpgrade:
                            results = self.sendRequestAndGetResult('city@upgradeBuilding', {"buildingId":needUpgrade})
                            if results['state'] == 0:
                                if results['data'].has_key('msg'):
                                    if results['data']['msg'] == "您的大理石不足":
                                        expBuild = getCache("expBuild")
                                        if needUpgrade not in expBuild:
                                            expBuild.append(needUpgrade)
                                        setCache("expBuild", expBuild)
                                    else:
                                        setCache("expBuild", [])
                                else:
                                    setCache("expBuild", [])
                            else:
                                setCache("expBuild", [])
                    else:
                        prints('建筑队列已满，不做升级建筑操作')
        except Exception as e:
            f = open('errorupgradeBuilding.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
#         try:
#             cityUpgrade = getCache('cityUpgrade')
#             if not isinstance(cityUpgrade, list):
#                 cityUpgrade = eval(cityUpgrade)
#             for citys in cityUpgrade: 
#                 #开始升级建筑
#                 self.sendRequestAndGetResult('city@upgradeBuilding', {"buildingId":citys})
#         
#         except Exception as e:
#             f = open('errorupgradeBuilding.txt','a')
#             traceback.print_exc(file=f)
#             f.flush()
#             f.close()
            
    #强化武将(武将星级)
    def upgradeBaowu(self):
        try:
            qianghua_bingzhong = getCache('qianghua_bingzhong')
            ifyongjiu = getCache('ifyongjiu')
            if not isinstance(qianghua_bingzhong, list):
                qianghua_bingzhong = eval(qianghua_bingzhong)
            for generals in qianghua_bingzhong: 
                #开始升级武将
#                 prints('开始升级武将%s'%generals)
                self.sendRequestAndGetResult('baowu@upgradeBaowu', {"generalId":generals})
                if ifyongjiu == "1":
                    self.sendRequestAndGetResult('general@foreverGeneral', {"generalId":generals})
        except Exception as e:
            f = open('errorupgradeBaowu.txt','a')
            traceback.print_exc(file=f)
            f.flush()
            f.close()
    #武将宝物升级(赏赐宝物) 
    
    def updateBaowu(self):
        ifzhongchengdu = getCache('zhongchengdu')
        if str(ifzhongchengdu) == '1':
            try:
                updateB = []
                generals = []
                result = self.sendRequestAndGetResult('playerBaowu@getBagEquip')
                results = []
                if result['state'] == 1:
                    if result['data'].has_key('baowus'):
                        results = result['data']['baowus']
                if len(results) > 0:
                    for baowus in results:
                        if int(baowus['attrs'][0]['att']) < 39 and int(baowus['attrs'][0]['def']) < 39:
                            updateB.append(baowus['storeId'])
                generalpanellist = self.sendRequestAndGetResult('general@getGeneralPanel')['data']['glist']
                for generalss in generalpanellist:
                    if len(updateB) > 0:
                        aa = self.sendRequestAndGetResult('playerBaowu@giveToG',{"storeId":updateB[0],"generalId":generalss['generalId']})
                        if aa['state'] <> 0 :
                            del updateB[0]
                del updateB
            except Exception as e:
                f = open('errorupdateBaowu.txt','a')
                traceback.print_exc(file=f)
                f.flush()
                f.close()
    #赏赐宝物选择版
#     def updateBaowu(self):
#         try:
#             updateB = []
#             generals = []
#             results = self.sendRequestAndGetResult('playerBaowu@getBagEquip')['data']['baowus']
#             if len(results) > 0:
#                 for baowus in results:
#                     if int(baowus['attrs'][0]['att']) < 39 and int(baowus['attrs'][0]['def']) < 39:
#                         updateB.append(baowus['storeId'])
# #             generalpanellist = self.sendRequestAndGetResult('general@getGeneralPanel')['data']['glist']
#             generalpanellist = getCache('qianghua_bingzhong')
#             for generalss in generalpanellist:
#                 if len(updateB) > 0:
#                     aa = self.sendRequestAndGetResult('playerBaowu@giveToG',{"storeId":updateB[0],"generalId":generalss})
#                     if aa['state'] <> 0 :
#                         del updateB[0]
#             del updateB
#             del generals
#         except Exception as e:
#             f = open('errorupdateBaowu.txt','a')
#             traceback.print_exc(file=f)
#             f.flush()
#             f.close()
    #跨服膜拜
    def kfmobai(self):
        need = 1
        self.sendRequestAndGetResult('kf@mobai')
        getIsAccFull = self.sendRequestAndGetResult('player@getIsAccFull')
        if getIsAccFull['state'] == 1:
            if getIsAccFull['data'].has_key('percent'):
                if int(getIsAccFull['data']['percent']) > 35:
#             if getIsAccFull['data'].has_key('isfull'):
#                 if int(getIsAccFull['data']['isfull']) == 1:
                    need = 0
        worlds = self.sendRequestAndGetResult('world@getInfo')
        if worlds['state'] == 1:
            if worlds['data'].has_key('gemStatueArray'):
                gemStatueArray = worlds['data']['gemStatueArray']
                for gems in gemStatueArray:
                    if str(getCache('force_id')) == str(gems['force']):
                        self.sendRequestAndGetResult('gem@mobai') 
        if need == 1:
            worldInfo = self.sendRequestAndGetResult('world@getInfo')
            max = 0
            minlevelUpTime = 1483313866010000
            pid = []
            if worldInfo['state'] == 1:
                prints('远征进度没有满，领取跨服金杯膜拜')
                if worldInfo['data'].has_key('statueArray'):
                    statueArray = worldInfo['data']['statueArray']
                    if len(statueArray) > 0:
                        for statueArrays in statueArray:
                            if statueArrays['playerLv'] >= max:
                                pid.append(statueArrays['playerId'])
            for p in pid:
                self.sendRequestAndGetResult('vs@mobai', {"pid":p})
            del pid
            #年兽膜拜
            nianshouinfo = self.sendRequestAndGetResult('springFestival@getNianshouInfo')
            if nianshouinfo['state'] == 1:
                if nianshouinfo['data'].has_key('canTimes'):
                    if int(nianshouinfo['data']['canTimes']) > 0: 
                        if nianshouinfo['data'].has_key('nianshouArrays'):
                            nianshouArrays = nianshouinfo['data']['nianshouArrays']
                            if len(nianshouArrays) > 0:
                                prints('开始膜拜年兽')
                                self.sendRequestAndGetResult('springFestival@mobaiNianshou',{"playerId":getCache('player_id')})
                                self.sendRequestAndGetResult('springFestival@mobaiNianshou',{"playerId":8378})
                                self.sendRequestAndGetResult('springFestival@mobaiNianshou',{"playerId":nianshouArrays[0]['playerId']})
                    
                    
            
    #春节红包活动
    def springFestival(self):
        springFestivals = self.sendRequestAndGetResult('springFestival@getInfo')
        if springFestivals['state'] == 1:
            freeTimes = 0
            if springFestivals['data'].has_key('freeTimes'):
                freeTimes = int(springFestivals['data']['freeTimes'])
            if freeTimes < 4:
                if springFestivals['data'].has_key('threeRewardState'):
                    threeRewardState = springFestivals['data']['threeRewardState']
                    prints('开启三送红包')
                    for i in range(0,len(threeRewardState)):
                        if str(threeRewardState[i]) == '1':
                            self.sendRequestAndGetResult('springFestival@threePlay', {"cardId":i+1})
            if springFestivals['data'].has_key('fortuneRewardState'):
                fortuneRewardState = springFestivals['data']['fortuneRewardState']
                for i in range(0,len(fortuneRewardState)):
                    if str(fortuneRewardState[i]) == '1':
                        prints('赐福成功后开启免费三次红包')
                        self.sendRequestAndGetResult('springFestival@fortunePlay', {"cardId":i+1})
#             if springFestivals['data'].has_key('rewardString'):
#                 rewardStrings = springFestivals['data']['rewardString']
#                 rewardString = rewardStrings.split(':')[0]
#                 if rewardString == 'gem':
#                     prints("我们只搞宝石")
            if springFestivals['data'].has_key('nationProcess'):
                nationProcess = springFestivals['data']['nationProcess']
                if nationProcess.has_key('state'):
                    if nationProcess['state'] == 1:
                        dayNum = springFestivals['data']['dayNum']
                        specialRewardState = springFestivals['data']['specialRewardState']
                        for i in range(len(specialRewardState)):
                            if dayNum == i + 1:
                                if str(specialRewardState[i]) <> '2':
                                    self.sendRequestAndGetResult('springFestival@fortunePlay', {"cardId":0})
                                    prints('第%s天还未拿到特殊奖励，开始金币开红包，消耗金币%s'%(int(specialRewardState[i])+1,springFestivals['data']['personGold']))
                                else:
                                    prints('第%s天已经拿到特殊奖励，停止金币开红包'%(int(specialRewardState[i])+1))
            if springFestivals['data'].has_key('bigRewardState'):
                if springFestivals['data']['bigRewardState'] == 1:
                    prints('领取大奖')
                    self.sendRequestAndGetResult('springFestival@getBigReward')
    
    def doEvents(self):
        eventsss = self.sendRequestAndGetResult('player@getAllActivity')
        if eventsss['state'] == 1:
            if eventsss['data'].has_key('acts'):
                eventss = eventsss['data']['acts']
                for events in eventss:
                    ids = str(events['id'])
                    if ids == '2':
                        #prints('充值送金免费领取')
                        self.payActivity()
                    elif ids == '3':
                        #prints('开始处理银币倾销免费')
                        self.copperDump()
                    elif ids == '4':
                        #prints('开始处理银币转盘免费')
                        self.copperturntable()
                    elif ids == '5':
                        #prints('兵书倾销免费买')
                        self.warcraftbookDump()
                    elif ids == '6':
                        #prints('宝石倾销免费次数')
                        self.gemDump()
                    elif ids == '7':
                        #prints('奇珍异宝免费购买')
                        self.generalTreasureActivity()
                    elif ids == '9':
                        #prints("宴请兵法免费领取")
                        self.warcraftCreater()
                    elif ids == '10':
                        #prints("军需品免费领取")
                        self.militarySupply()
                    elif ids == '11':
                        #prints("祖传兵书免费领取")
                        self.warcraftlvup()
                    elif ids == '12':
                        #prints("捞玉玺免费领取")
                        self.laoyuxi()
                    elif ids == '13':
                        #prints('开始处理草船借箭——宝石版免费')
                        self.caoChuan()
                    elif ids == '14':
                        #prints('开始处理草船借箭——兵书版免费')
                        self.caoBook()
        #             elif ids == '15':
        #                 #prints('七擒孟获——免费追击')
        #                 self.arrestMenghuo()
                    elif ids == '16':
                        #prints('曹操起兵——免费次数')
                        self.helpCaocao()
                    elif ids == '17':
                        #prints('三顾茅庐（兵书版）——免费次数')
                        self.threeVisits()
#                     elif ids == '17':
#                         #prints('三顾茅庐——免费次数')
#                         self.threeVisits()
                    elif ids == '21':
                        #prints('三顾茅庐（宝石版）——免费次数')
                        self.threeVisits2()
                    elif ids == '20':
                        #prints('元旦活动——免费次数')
                        self.newYears()
                    elif ids == '22':
                        #prints('春节红包活动')
                        self.springFestival()
                    elif ids == '23':
                        #prints('春节红包活动')
                        self.laobaowu()
    
    def upgradeZhugongbaowu(self):
        zhugongbaowu_list = getCache('zhugongbaowu')
        if not isinstance(zhugongbaowu_list, list):
            zhugongbaowu_list = eval(zhugongbaowu_list)
        if isinstance(zhugongbaowu_list, list):
            for i in range(len(zhugongbaowu_list)):
                if str(zhugongbaowu_list[i]) == '1':
                    prints("主公宝物升级位置：%s"%(i+1))
                    self.sendRequestAndGetResult('playerBaowu@upgrade', {"pos":i+1})
    
    def leitai(self):
        try:
            worldInfo = self.sendRequestAndGetResult("world@getInfo")
            force_id = getCache('force_id')
            if str(force_id) == "1":
                city = 121
            elif str(force_id) == "1":
                city = 122
            else:
                city = 123
            if worldInfo['data'].has_key('cities'):
                for cities in worldInfo['data']['cities']:
                    if city == cities['cityId']:
                        if cities.has_key("leitaiReward"):
                            self.sendRequestAndGetResult("leitai@getReward")
        except Exception as e:
                f = open('errorleitai.txt','a')
                traceback.print_exc(file=f)
                f.flush()
                f.close()
    def doSomething2(self):
        prints("基础任务——庆典、战斗处理开始")  
        prints('开始庆典、战斗处理')
        self.celebration()
        prints('一轮基础任务——庆典、战斗完成，等待%s秒'%1)
        time.sleep(1)
    
    
    def doSomething3(self): 
        prints("基础任务——建筑其他操作")
        self.building()
        prints('一轮基础任务——建筑其他操作完成，等待%s秒'%1)
        time.sleep(1)
        
    def doSomething4(self):
        prints("基础任务——收粮和银币开始")   
        self.building2()
        prints('一轮基础任务——收粮和银币完成，等待%s秒'%1)
        time.sleep(1)
        
        
    def doSomething(self):
#         prints(getCache('zhugongbaowu'))
        prints('玩家名为：'+str(getCache('playerName')))
        prints('玩家等级为：'+str(getCache('playerLvs')))
        prints('玩家id为：'+str(getCache('player_id')))
        prints('国家id为：'+str(getCache('force_id')))
        # 小秘书领取攻城奖励
        #主公宝物升级
        self.upgradeZhugongbaowu()
        self.secretary()
#         prints('远征/1V2主的排除的玩家：%s'%getCache('exceptss'))
        for a in getCache('exceptss'):
            prints('远征/1V2主的排除的玩家：%s'%a)
        if str(getCache('player_id')) == '8378':
#             prints("西门大官人审批大理石")
            self.sendRequestAndGetResult('marble@agreeMarble', {"type":1,"applyId":178})
            self.sendRequestAndGetResult('marble@agreeMarble', {"type":1,"applyId":110})
#         prints('开始赎回武将')
        self.getbackgeneral()
        if int(getCache('playerLvs')) > 10:
#         prints('开始通商+民工事件')
            self.trade()
#         prints("开始邀功")
        self.sendRequestAndGetResult("city@multiPrestige")
#         #活动处理
        self.doEvents()
#         prints('跨服膜拜')
        #跨服金杯膜拜
        self.kfmobai()
        self.sendRequestAndGetResult('nation@getAllOcpyReward')
#         prints('开始处理国防建设')
        self.guofang()
        #使用兵书
        self.upgradeWarcraft()
        #免费祭祀
        self.dofete()
        #开始处理宝石
        self.doGem()
        prints('开始处理武将忠诚度升级')
        self.updateBaowu()
        #强化武将
#         if getCache('needGeneralUpgrade')%30 == 0:
        self.upgradeBaowu()
        #投资武将
        self.touziGeneral()
        setCache('needGeneralUpgrade', getCache('needGeneralUpgrade')+1)
        #升级建筑
        self.upgradeBuilding()
        #国家擂台
        self.leitai()
        prints('一轮附加任务完成，等待%s秒，日志将会清空'%(self.sleepTime*3))
        time.sleep(self.sleepTime*2)
        
        
    def __init__(self):
        self.getCjAndOpener()
        